<template>
  <q-page class="q-pa-md project-detail" v-loading="loading">
    <q-breadcrumbs class="" style="height: 40px; line-height: 40px">
      <q-breadcrumbs-el label="项目概览" />
    </q-breadcrumbs>
    <div class="q-mt-md">
      <el-row :gutter="20" class="detail-row">
        <el-col :span="6" class="project-overview">
          <el-card flat bordered class="detail-card">
            <p style="margin: 0">基本信息</p>
            <q-card-section>
              <el-form label-width="80px" :label-position="'left'">
                <el-form-item label="项目名称">
                  {{ menuStore.currentProject.title }}</el-form-item
                >
                <el-form-item label="项目说明">
                  {{ menuStore.currentProject.description }}</el-form-item
                >
<!--                <el-form-item label="创建人">-->
<!--                  {{ menuStore.currentProject.creator.username }}</el-form-item-->
<!--                >-->
                <el-form-item label="创建时间">
                  {{ menuStore.currentProject.create_at }}</el-form-item
                >
<!--                <el-form-item label="项目成员">-->
<!--                  {{ menuStore.currentProject.members.length }}-->
<!--                </el-form-item>-->
              </el-form>
            </q-card-section>
          </el-card>
        </el-col>
        <el-col :span="18">
          <el-card flat bordered class="detail-card">
            <p style="margin: 0">快捷操作</p>
            <q-card-section>
              <div class="row shortcut">
                <div
                  class="col col-2"
                  v-for="(item, index) in shortcutArr"
                  :key="index"
                  style="text-align: center"
                >
                  <div class="block">
                    <el-image
                      style="width: 56px; height: 56px"
                      :src="item.icon"
                      fit
                    />
                  </div>
                  <b>{{ item.title }}</b>
                  <div class="textConttent" v-html="item.textContent"></div>
                  <div>
                    <div class="bottomData">
                      <div
                        v-for="(dataItem, index) in item.dataList"
                        :key="index"
                        style="margin-right: 3px"
                      >
                        <div class="titleBox">{{ dataItem.str }}</div>
                        <div class="numberBox">{{ dataItem.num }}</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </q-card-section>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <div class="q-mt-md">
      <el-row :gutter="24" class="detail-row">
        <el-col :span="24">
          <el-card flat bordered class="detail-card">
            <p style="margin: 0">最近的工作</p>
            <q-card-section class="flex">
              <el-table
                ref="tableList"
                :data="filterTableData"
                :row-key="row => row.id"
                style="width: 100%;font-size: 12px;"
                :header-cell-style="{ background: '#eee', color: '#333333' }"
                :expand-row-keys="expandRows"
                @expand-change="handleExpandChange"
              >
                <TransitionGroup name="el-fade-in-linear">
                  <el-table-column align="center" width="40" type="expand">
                    <template v-slot="props">
                      <el-table :data="tableData" style="width: 100%;font-size: 12px;"
                                :header-cell-style="{ background: '#f8f8f8', color: '#333333' }">
                        <el-table-column align="center" prop="" label="" width="40" />
                        <el-table-column align="center" prop="version_number" label="版本号" width="280">
                          <template #default="scope">
                            <el-button link type="primary" size="small" @click="toModelVersion(scope.row,props.row)">{{ scope.row.version_number }}</el-button>
                          </template>
                        </el-table-column>
                        <el-table-column align="center" prop="dockerStatus" label="状态"  width="200" />
                        <el-table-column align="center" prop="create_at" label="创建时间" width="200" />
                        <el-table-column align="center" prop="description" label="版本说明" width="200" />
                        <el-table-column align="center" prop="labels" label="操作" width="250">
                          <template #default="scope">
                            <el-button v-show="(scope.row.dockerStatus !== '构建中' && scope.row.dockerStatus !== '构建失败' && scope.row.dockerStatus !== '初始化')?userStatus?true: scope.row.creator_username == userInfoName?true:false: false" link type="primary" size="small" @click="toModelDevelopMent">部署</el-button>
                            <el-button v-show="(scope.row.dockerStatus !== '构建中' && scope.row.dockerStatus !== '构建失败' && scope.row.dockerStatus !== '初始化')?userStatus?true: scope.row.creator_username == userInfoName?true:false: false" link type="primary" size="small" @click="toModelVersion(scope.row,props.row)">评估报告</el-button>
                            <el-button v-show="userStatus?true:scope.row.creator_username == userInfoName?true:false" link type="primary" size="small" @click="deleteModelVersionHandle(scope.row,scope.$index)">删除</el-button>
                            <el-button v-show="(scope.row.dockerStatus !== '构建中' && scope.row.dockerStatus !== '构建失败' && scope.row.dockerStatus !== '初始化')?userStatus?true: scope.row.creator_username == userInfoName?true:false: false" link type="primary" size="small" @click.stop="mirrorAddressDialog(scope.row,$event)">镜像地址</el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </template>
                  </el-table-column>
                </TransitionGroup>
                <el-table-column align="center" prop="title" label="模型名称" width="120" >
                  <template #default="scope">
                    <el-button link type="primary" size="small" @click="toDataSetDetail(scope.row)">{{ scope.row.title }}</el-button>
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="latest_version_number" label="最新版本" width="150" />
                <el-table-column align="center" prop="create_at" label="创建时间" width="200" />
                <el-table-column align="center" prop="versions_count" label="版本数量" width="200" />
                <el-table-column align="center" prop="description" label="描述" width="200" />
                <el-table-column align="center" prop="labels" label="操作">
                  <template #default="scope">
                    <el-button v-show="userStatus?true:scope.row.creator_username == userInfoName" link type="primary" size="small" @click="addVersion(scope.row,$event)">新增版本</el-button>
                    <el-button v-show="userStatus?true:scope.row.creator_username == userInfoName" link type="primary" size="small" @click="deleteModelFun(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </q-card-section>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <el-dialog v-model="deleteModelDialog" :show-close="false" width="500px" :close-on-click-modal="false">
      <template #header="{}">
        <div style="display: flex;justify-content:space-between;margin-top: 10px">
          <div style="display:flex;">
            <el-icon style="font-size: 20px; color: #FFA940"><WarningFilled /></el-icon>
            <span style="margin-left: 10px;color: #1D1D1D;font-weight: bold">删除提醒</span>
          </div>
        </div>
      </template>
      <div style="margin: 10px 0 0px 50px;padding: 0">
        <p>确定删除本模型的所有版本吗?</p>
        <p>删除后不可恢复,请谨慎操作！</p>
      </div>
      <div style="display: flex;justify-content: flex-end;padding-bottom: 10px">
        <el-button type="primary" @click="deleteModelDialog = false">放弃删除</el-button>
        <el-button @click="emitDeleteCreateModel">继续删除</el-button>
      </div>
    </el-dialog>
    <el-dialog v-model="deleteModelVersionDialog" :show-close="false" width="500px" :close-on-click-modal="false">
      <template #header="{}">
        <div style="display: flex;justify-content:space-between;margin-top: 10px">
          <div style="display:flex;">
            <el-icon style="font-size: 20px; color: #FFA940"><WarningFilled /></el-icon>
            <span style="margin-left: 10px;color: #FFA940;font-weight: bold">删除提醒</span>
          </div>
        </div>
      </template>
      <div style="margin: 10px 0 0 50px;">
        <p style="letter-spacing:2px;">确定删除本模型的{{ modelVersionInfo.version_number }}版本吗?</p>
        <p style="letter-spacing:2px;">删除后不可恢复,请谨慎操作！</p>
      </div>
      <div style="display: flex;justify-content: flex-end;padding: 10px 0">
        <el-button type="primary" @click="deleteModelVersionDialog = false">放弃删除</el-button>
        <el-button @click="emitDeleteModelVersion">确认删除</el-button>
      </div>
    </el-dialog>
    <!--镜像弹框-->
    <el-dialog v-model="mirrorAddressDialogShow" :show-close="false" width="500px" :close-on-click-modal="false">
      <template #header="{}">
        <div style="display: flex;justify-content:space-between;margin-top: 10px">
          <div style="display:flex;">
            <span style="margin-left: 10px;color: #1D1D1D;font-weight: bold">镜像地址</span>
          </div>
        </div>
      </template>
      <div style="display: flex; padding-left: 60px;align-items: center;margin-top: 20px">
        镜像地址: <el-input disabled="false" style="width: 80%;margin-left: 10px" v-model="mirrorAddressValue" spellcheck="false"></el-input>
      </div>
      <div style="display: flex;width: 100%;padding: 0;margin-top: 40px;border-top: 1px solid rgb(234,234,234);padding: 5px 0">
        <div style="flex: 1;text-align: center;line-height: 30px;cursor: pointer;border-right: 1px solid rgb(234, 234, 234)" @click="mirrorAddressDialogShow = false">返回</div>
        <div style="flex: 1;text-align: center;line-height: 30px;color: rgb(58,141,255);cursor: pointer" @click="copyButton">复制</div>
      </div>
    </el-dialog>


    <!--新增模型版本 start-->
    <el-dialog v-model="addVersionDialogShow" :show-close="false" width="500px" :close-on-click-modal="false">
      <template #header="{}">
        <div style="display: flex;justify-content:space-between;margin-top: 10px">
          <div style="display:flex;">
            <span style="margin-left: 10px;color: #1D1D1D;font-weight: bold;letter-spacing: 1px">新增模型版本</span>
          </div>
        </div>
      </template>
      <el-form
        ref="addVersionFormRef"
        :model="addVersionForm"
        :rules="addVersionRules"
        label-width="140px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="模型名称:">
          <p style="margin: 0">{{ ModelDetailInfo.title }}</p>
        </el-form-item>
        <el-form-item label="最新版本:">
          <p style="margin: 0">{{ ModelDetailInfo.latest_version_number }}</p>
        </el-form-item>
        <el-form-item label="请输入当前版本:" prop="version_number">
          <el-input v-model="addVersionForm.version_number" :placeholder="Number(ModelDetailInfo.latest_version_number) + 1" />
        </el-form-item>
        <el-form-item label="描述:" prop="description">
          <el-input type="textarea" :rows="3" v-model="addVersionForm.description" />
        </el-form-item>
        <el-form-item label="选择算法:" prop="description">
          <p style="margin: 0">{{ ModelDetailInfo.model_title }}</p>
        </el-form-item>
        <el-form-item label="选择训练作业：" prop="model_run_id">
          <el-select v-model.trim="addVersionForm.model_run_id" placeholder="请选择训练作业" prop="model_run_id">
            <el-option v-for="item in modelRunsData" :key="item.title" :label="item.title" :value="item.id" />
          </el-select>
        </el-form-item>
        <div style="display: flex;width: 100%;border-top: 1px solid rgb(234,234,234);padding: 5px 0">
          <div style="flex: 1;text-align: center;line-height: 30px;cursor: pointer;margin-bottom: 0;border-right: 1px solid rgb(234, 234, 234)" @click="cancelAddVersion(addVersionFormRef)">取消</div>
          <div style="flex: 1;text-align: center;line-height: 30px;color: rgb(58,141,255);cursor: pointer;margin-bottom: 0" @click="addModel(addVersionFormRef)">完成创建</div>
        </div>
      </el-form>
    </el-dialog>
  </q-page>
</template>
<script setup lang="ts">
import {ref, reactive, toRaw, computed, shallowRef} from 'vue';
import { useRouter } from 'vue-router';
import { useMenuStore } from 'src/stores/menu';
import iconurl1 from 'assets/indexPageIcon/v2_rgosvm.png';
import iconurl2 from 'assets/indexPageIcon/v2_rfewvm_1.png';
import iconurl3 from 'assets/indexPageIcon/v2_rfewvm_2.png';
import iconurl4 from 'assets/indexPageIcon/v2_rfewvm_3.png';
import iconurl5 from 'assets/indexPageIcon/v2_rfewvm_4.png';
import { modelStore } from 'src/stores/model';
const showModelStore = modelStore()
import {
  addModelVersion, deleteCreateModel, deleteModelVersion,
  getCreateModelAppList,
  getCreateModelDetail,
  getModelAboutRuns,
  getModelSource,
  getModelVersionsList
} from "src/api/model";
import {ElMessage, FormInstance} from "element-plus";
import useClipboard from "vue-clipboard3";
const menuStore = useMenuStore();
const loading = ref(false);
const router = useRouter();
const projectId = router.currentRoute.value.params.project_id;
const userStatus = JSON.parse(localStorage.getItem('user') || '{}').status; //判断用户是否是项目创建人或项目管理员
const userInfoName = localStorage.getItem('username'); //获取用户登录的用户名
let mirrorAddressValue = ref('');
let mirrorAddressDialogShow = ref(false);
const addVersionForm = reactive({
  title: '',
  version_number: '',
  description: '',
  model_run_id: ''
});
const addVersionRules = reactive({
  version_number: [
    { required: true, message: '请输入当前版本号', trigger: 'change' },
  ],
  model_run_id: [
    { required: true, message: '训练作业不能为空', trigger: 'blur' }
  ]
});
const addVersionFormRef = ref()
const shortcutArr = reactive([
  {
    icon: iconurl1,
    title: '数据管理',
    textContent: '支持用户上传数据<br>到后台进行托管',
    dataList: [
      {
        str: '数据集',
        num: 10,
      },
      {
        str: '特征库',
        num: 10,
      },
    ],
  },
  {
    icon: iconurl5,
    title: '算法管理',
    textContent: '支持主流git仓<br>库对接',
    dataList: [
      {
        str: '算法',
        num: 2,
      },
    ],
  },
  {
    icon: iconurl3,
    title: '训练作业',
    textContent: '支持异构分布式<br>基础资源',
    dataList: [
      {
        str: '训练',
        num: 2,
      },
    ],
  },
  {
    icon: iconurl4,
    title: '模型应用',
    textContent: '为所有模型提供<br>统一的管理',
    dataList: [
      {
        str: '模型',
        num: 2,
      },
    ],
  },
  {
    icon: iconurl2,
    title: '模型部署',
    textContent: '支持将模型转换为适合<br>业务场景的推理模式',
    dataList: [
      {
        str: '部署',
        num: 2,
      },
      {
        str: '服务',
        num: 2,
      },
    ],
  },
  {
    icon: iconurl4,
    title: '设计器建模',
    textContent: '可自由拖拽式算子建<br>模',
    dataList: [
      {
        str: '建模',
        num: 2,
      },
    ],
  },
]);





const tableList = ref();
const repository_model_id = ref(0);
const tableData = ref([]);
let expandRows = reactive([]);
const searchName = ref('')
let labelAssignData = ref(
  {
    count: 0,
    next: null,
    previous: null,
    results: []
  }
);
const filterTableData = computed(() =>
  labelAssignData.value.results.filter(
    (data:any) =>
      !searchName.value ||
      data.title.toLowerCase().includes(searchName.value.toLowerCase())
  )
)

const deleteModelDialog = ref(false)
let modelListItem = ref({});
function deleteModelFun(row:any) {
  deleteModelDialog.value = true
  modelListItem.value = toRaw(row)
}
//删除创建的模型
function emitDeleteCreateModel () {
  const id = toRaw(modelListItem.value.id)
  deleteCreateModel(projectId, id).then((res:any) => {
    ElMessage.success("删除成功！！！")
    deleteModelDialog.value = false;
    getModelAppList();
  })
}



getModelAppList();
function getModelAppList () {
  loading.value = true;
  getCreateModelAppList(projectId).then((res:any) => {
    loading.value = false;
    res.data.results.forEach( (items:any) => {
      items.children = [];
      items.hasChildren = true;
    })
    labelAssignData.value = res.data;
  })
}
function emitDeleteModelVersion () {
  deleteModelVersion(projectId,repository_model_id.value,modelVersionInfo.value.id).then( (res:any) => {
    ElMessage.success(`成功删除模型版本！！！`)
    deleteModelVersionDialog.value = false;
    tableData.value.splice(indexs.value,1);
  })
}
function toDataSetDetail(row:any){
  const id = toRaw(row.id)
  showModelStore.setRepositoryModelId(id);
  router.push({ name: 'model-app-detail', params: { project_id: projectId } })
}
const cancelAddVersion = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  addVersionDialogShow.value = false;
}
const addModel = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      const model_idData = ModelDetailInfo.value.id;
      let params = ref({
        title: ModelDetailInfo.value.title,
        version_number: addVersionForm.version_number,
        description: addVersionForm.description,
        model_run_id: addVersionForm.model_run_id
      })
      addModelVersion(projectId,model_idData,params.value).then( (res:any) => {
        ElMessage.success("版本创建成功！！！");
        addVersionDialogShow.value = false;
        formEl.resetFields();
        getModelAppList();
      })
    }
  })
}
//新增版本
let addVersionDialogShow = ref(false);
function addVersion(row:any,e:any){
  tableList.value.toggleRowExpansion(row,true)
  addVersionDialogShow.value = true;
  getModelDetail(row.id);
}
let ModelDetailInfo = ref({})
//存放获取所有的训练任务
const modelRunsData = shallowRef([])
let ModelSource = ref({})
function getModelDetail (repository_model_id:any) {
  getCreateModelDetail(projectId,repository_model_id).then( (res:any) => {
    // const model_id = res.data.model_id
    ModelDetailInfo.value = res.data;
    getModelAboutRuns(projectId, res.data.model_id).then((res: any) => {
      loading.value = false;
      modelRunsData.value = res.data.filter( (items:any) => items.status === 'success' );
    }).finally(() => {
      loading.value = false;
    }).catch(error => {
      console.log(error)
    })
    // getModelSource(projectId,model_id).then( (res:any) => {
    //   ModelSource.value = res.data.filter( (items:any) => items.status === 'success' );
    //   console.log('ModelSource',ModelSource)
    // })
  })
}
//删除模型版本
const modelVersionInfo = ref({})
let indexs = ref(0)
let deleteModelVersionDialog = ref(false)
function deleteModelVersionHandle (row:any,index:any) {
  indexs.value = index;
  modelVersionInfo.value = toRaw(row)
  deleteModelVersionDialog.value = true
}
//评估报告
function toModelVersion(row:any,prow:any){
  showModelStore.setRepositoryModelId(toRaw(prow.id));
  showModelStore.setVersionId(toRaw(row.id))
  router.push({ name: 'assessment-report', params: { project_id: projectId } })
}
//跳转模型部署界面
const toModelDevelopMent = () => {
  router.push({ name: 'model-deployment', params: { project_id: projectId } })
}
//镜像地址弹框
function mirrorAddressDialog (row:any,event:any) {
  event.stopPropagation();
  mirrorAddressValue.value = row.docker_image_address
  mirrorAddressDialogShow.value = true;
}
// 复制镜像地址
const { toClipboard } = useClipboard()
const copyButton = async () => {
  try {
    await toClipboard(mirrorAddressValue.value)
    ElMessage({
      message: '数据集链接已复制',
      type: 'success',
    })
  } catch (e) {
    console.error(e)
  }
}
function handleExpandChange(row:any, rows:any) {
  if( rows.length > 1 ){
    tableList.value.toggleRowExpansion(rows[0])
  }
  repository_model_id.value = toRaw(row.id);
  const isExpend = rows.some((r:any) => r.id === row.id) // 判断当前行展开状态
  if (isExpend) {
    getModelVersionsList(projectId,repository_model_id.value).then((res:any) => {
      res.data.forEach( (item:any) => {
        item.dockerStatus = dockerStatusChage(item.docker_image_status);
      })
      tableData.value = res.data;
    }).catch( (error:any) => {
      ElMessage.success("数据列表请求失败！！！")
    })
  } else {
    return
  }
}
function dockerStatusChage(dockerStatus:any){
  switch (dockerStatus) {
    case 'building':
      return '构建中';
    case 'available':
      return '构建成功';
    case 'fail':
      return '构建失败';
    case 'initial':
      return '初始化';
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body{
  padding-top: 0;
  padding-bottom: 0;
}
::v-deep .el-dialog__header {
  padding: 10px 0 0 10px;
  margin: 0;
  border-bottom: 1px solid rgb(234,234,234);
  div{
    margin-bottom: 5px;
  }
}
.project-detail {
  .project-overview .el-form-item {
    margin-bottom: 0px;

    .el-form-item__content {
      word-break: break-all;
      color: $grey-8;
    }

    .el-form-item__label {
      color: $grey-10;
    }
  }

  .detail-row {
    .detail-card {
      height: 100%;
      .el-card__body {
        padding: 10px;
      }
    }

    ul {
      margin: 0;
      padding-left: 20px;

      li {
        line-height: 32px;

        span {
          color: $primary;
          font-size: 18px;
        }
      }
    }
  }
  .overlapping {
    border: 2px solid white;
    position: absolute;
  }

  .el-table thead {
    color: unset;
  }
}
.latelyTop {
  position: relative;
  margin-bottom: 15px;
}

.bottomData {
  display: flex;
  justify-content: center;
  margin-top: 10px;
  .titleBox {
    width: 57px;
    border: 1px solid #bbb;
    background-color: rgba($color: #e6f7ff, $alpha: 1);
    border-radius: 3px;
    padding: 5px 2px;
    font-size: 13px;
    margin-right: 2px;
  }

  .numberBox {
    border: 1px solid #bbb;
    background-color: rgba($color: #1484fc, $alpha: 1);
    border-radius: 3px;
    padding: 5px 2px;
    font-size: 13px;
    margin-right: 2px;
    color: white;
  }
}

.lateData {
  &:nth-child(1),
  &:nth-child(3),
  &:nth-child(5) {
    .bottomData {
      margin-left: -20px;
    }
  }

  &:nth-child(2),
  &:nth-child(4) {
    .bottomData {
      margin-left: 7px;
    }
  }
}
</style>
